import React, { useState } from 'react';
import Web3 from 'web3';
import styles from './components.module.less';
import { Button, Input, Typography } from 'antd';
import { observer } from 'mobx-react-lite';

interface TransactionProps {
  web3: Web3 | null;
  account: string;
  isConnected: boolean;
  onResult: (result: string) => void;
}

const Transaction = observer(({ web3, account, isConnected, onResult }: TransactionProps) => {
  const [recipient, setRecipient] = useState<string>('');
  const [amount, setAmount] = useState<string>('0.001');

  // 发送交易
  const sendTransaction = async () => {
    if (!web3 || !account || !isConnected) return;

    if (!recipient.trim()) {
      alert('请输入接收方地址');
      return;
    }

    const amountValue = parseFloat(amount);
    if (isNaN(amountValue) || amountValue <= 0) {
      alert('请输入有效的转账金额');
      return;
    }

    try {
      // 显示加载状态
      onResult('正在发送交易...');
      
      // 发送指定金额的ETH到指定地址
      const txHash = await (window as any).ethereum.request({
        method: 'eth_sendTransaction',
        params: [{
          from: account,
          to: recipient,
          value: web3.utils.toHex(web3.utils.toWei(amount.toString(), 'ether'))
        }]
      });
      
      onResult('交易发送成功，哈希值: ' + txHash);
      console.log('交易发送成功:', txHash);
      
      // 可以添加交易状态查询功能
      setTimeout(() => {
        onResult('交易已发送，请在区块链浏览器上查看状态:\n' + 
          'https://etherscan.io/tx/' + txHash);
      }, 3000);
      
    } catch (error) {
      console.error('发送交易失败:', error);
      if ((error as any).code === 4001) {
        onResult('交易被取消: 您拒绝了MetaMask的交易确认请求');
      } else {
        onResult('发送交易失败: ' + (error as Error).message);
      }
    }
  };

  // 发送测试交易（发送给自己）
  const sendTestTransaction = async () => {
    if (!web3 || !account || !isConnected) return;

    try {
      onResult('正在发送测试交易...');
      
      const txHash = await (window as any).ethereum.request({
        method: 'eth_sendTransaction',
        params: [{
          from: account,
          to: account,
          value: web3.utils.toHex(web3.utils.toWei('0.001', 'ether'))
        }]
      });
      
      onResult('测试交易发送成功，哈希值: ' + txHash);
      console.log('测试交易发送成功:', txHash);
    } catch (error) {
      console.error('发送测试交易失败:', error);
      if ((error as any).code === 4001) {
        onResult('测试交易被取消: 您拒绝了MetaMask的交易确认请求');
      } else {
        onResult('发送测试交易失败: ' + (error as Error).message);
      }
    }
  };

  const isUsingPublicNode = account === '使用公共节点连接';

  return (
    <div className={styles.transaction}>
      <Typography.Title level={4}>转账功能</Typography.Title>
      
      <div className={styles.inputGroup}>
        <label>接收方地址:</label>
        <Input
          value={recipient}
          onChange={(e) => setRecipient(e.target.value)}
          placeholder="0x..."
          disabled={!isConnected || isUsingPublicNode}
        />
      </div>
      
      <div className={styles.inputGroup}>
        <label>转账金额 (ETH):</label>
        <Input
          value={amount}
          onChange={(e) => setAmount(e.target.value)}
          min="0.0001"
          step="0.0001"
          disabled={!isConnected || isUsingPublicNode}
        />
      </div>
      
      <div className={styles.buttonGroup}>
        <Button
          type="primary"
          onClick={sendTransaction}
          className={styles.actionButton}
          disabled={!isConnected || isUsingPublicNode || !recipient || parseFloat(amount) <= 0}
        >发送转账</Button>
        
        <Button
          onClick={sendTestTransaction}
          className={styles.actionButton}
          disabled={!isConnected || isUsingPublicNode}
        >发送测试交易</Button>
      </div>
      
      {isUsingPublicNode && (
        <Typography.Paragraph className={styles.note}>提示: 发送交易需要连接MetaMask钱包</Typography.Paragraph>
      )}
    </div>
  );
});

export default Transaction;
